#实时检测，性能不错

import cv2
import mediapipe as mp
from timecacu import getTimer


def captureFaceVideo(video):
    # 初始化Mediapipe人脸检测器
    mp_face_detection = mp.solutions.face_detection
    face_detection = mp_face_detection.FaceDetection()

    # 打开摄像头
    cap = cv2.VideoCapture(video)
    t = getTimer("mediapipe")


    while True:
        # 读取视频帧
        ret, frame = cap.read()
        t.start()
        nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # 进行人脸检测
        results = face_detection.process(nframe)
        t.end()

        # 绘制人脸框
        if results.detections:
            for detection in results.detections:
                bbox = detection.location_data.relative_bounding_box
                ih, iw, _ = frame.shape
                x, y, w, h = int(bbox.xmin * iw), int(bbox.ymin * ih), int(bbox.width * iw), int(bbox.height * ih)
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # 显示结果
        cv2.imshow('Face Detection', frame)

        # 按下q键退出
        if cv2.waitKey(1) == ord('q'):
            break

    t.show()
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

# 实际证明已经是短程了，缩小后识别不出来
captureFaceVideo(0)